// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: 'dazhentan-air'
})
const db = cloud.database()
const _ = db.command
var xlsx = require('node-xlsx');
const MAX_LIMIT = 100
// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event)
  switch (event.action) {
    case 'askrequest': {
      return askrequest(event)
    }
    case 'excel': {
      return excel(event)
    }
    case 'getexcel': {
      return getexcel(event)
    }
    case 'getexcel_data': {
      return getexcel_data(event)
    }
    case 'getlocation': {
      return getlocation(event)
    }
    case 'getmyreq': {
      return getmyreq(event)
    }
    case 'getuserdata': {
      return getuserdata(event)
    }
    case 'getuserrequest': {
      return getuserrequest(event)
    }
    case 'knowing': {
      return knowing(event)
    }
    case 'pin': {
      return pin(event)
    }
    case 'signin': {
      return signin(event)
    }
    case 'signip': {
      return signip(event)
    }
    default: {
      return
    }
  }
}

async function askrequest(event) {
  if (event.per) {
    var data = cloud.database().collection("request").where({
      name: event.username
    }).update({
      data: {
        permission: 1
      }
    })
  } else {
    var data = cloud.database().collection("request").where({
      name: event.username
    }).update({
      data: {
        permission: 0
      }
    })
  }
}

async function excel(event) {
  db.collection('user').where({
    _id: _.exists(true)
  }).remove()
  let {
    fileID
  } = event
  //1,通过fileID下载云存储里的excel文件
  const res = await cloud.downloadFile({
    fileID: fileID,
  })
  const buffer = res.fileContent
  const all_excel_data = [] //用来存储所有的excel数据
  //2,解析excel文件里的数据
  var sheets = xlsx.parse(buffer); //获取到所有sheets
  sheets.forEach(function (sheet) {
    console.log(sheet['name']);
    for (var rowId in sheet['data']) {
      //console.log(rowId);
      var row = sheet['data'][rowId]; //第几行数据
      if (rowId > 0 && row) { //第一行是表格标题，所以我们要从第2行开始读
        //3，把解析到的数据存到excelList数据表里
        var sux = row[4];
        all_excel_data.push({
          department: row[0],
          num: row[1],
          name: row[2],
          seatnum: row[3],
          notice: row[4],
          signin: false
        })
      }
    }
  });
  // 一起添加所有数据
  var result = await db.collection('user').add({
    data: all_excel_data
  }).then(res => {
    return res
  }).catch(err => {
    return err
  })
  return result
}

async function getexcel(event) {
  try {
    let {
      userdata
    } = event

    //1,定义excel表格名
    let dataCVS = 'download.xlsx'
    //2，定义存储数据的
    let alldata = [];
    let row = ['班级', '姓名', '学号', '座位号', '签到状态']; //表属性
    alldata.push(row);

    for (let key in userdata) {
      let arr = [];
      arr.push(userdata[key].department);
      arr.push(userdata[key].name);
      arr.push(userdata[key].num);
      arr.push(userdata[key].seatnum);
      arr.push(userdata[key].signin);
      alldata.push(arr)
    }
    //3，把数据保存到excel里
    var buffer = await xlsx.build([{
      name: "Sheet",
      data: alldata
    }]);
    //4，把excel文件保存到云存储里
    return await cloud.uploadFile({
      cloudPath: dataCVS,
      fileContent: buffer, //excel二进制文件
    })

  } catch (e) {
    console.error(e)
    return e
  }
}

async function getexcel_data(event) {
  const wxContext = cloud.getWXContext()
  // 先取出集合记录总数
  const countResult = await db.collection("user").count()
  const total = countResult.total
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection("user").skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
      openid: wxContext.OPENID
    }
  })
}

async function getlocation(event) {
  var data = db.collection("location").where({
    location: _.exists(true),
  }).get()
  return data
}

async function getmyreq(event) {
  var data = db.collection("request").where({
    req: _.exists(true),
    name: event.name,
    permission: _.exists(true)
  }).get()
  return data
}

async function getuserdata(event) {
  var data = cloud.database().collection("user").where({
    signin: false
  }).get()
  return data
}

async function getuserrequest(event) {
  var data = cloud.database().collection("request").where({
    req: _.exists(true),
    permission: 2
  }).get()
  return data
}

async function knowing(event) {
  console.log(event.department)
  var data = cloud.database().collection("dormitories").add({
    data: {
      舍寝: event.department,
      扣分项: event.gg
    }
  })
  return data;
}

async function pin(event) {
  console.log(event.department)
  var data = cloud.database().collection("request").add({
    data: {
      department: event.department,
      name: event.name,
      req: event.req,
      permission: 2
    }
  })
  return data;
}

async function signin(event) {
  var data = cloud.database().collection("user").where({
    department: event.department,
    name: event.name,
    num: event.num,
  }).update({
    data: {
      signin: true
    }
  })
}

async function signip(event) {
  console.log(event)
  var data = cloud.database().collection("user").where({
    department: event.department,
    name: event.name,
    num: event.num,
  }).update({
    data: {
      ip: event.ip
    }
  })
  return data
}